
package cnhy.salary.controller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cnhy.salary.cfg.PayPowers;
import cnhy.salary.domain.Department;
import cnhy.salary.domain.Employee;
import cnhy.salary.domain.dto.EmployeeDto;
import cnhy.salary.domain.dto.WageDictCfg;
import cnhy.salary.service.EmployeeSvc;
import cnhy.salary.service.WageSvc;
import com.easy.query.core.api.dynamic.sort.ObjectSort;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import io.swagger.annotations.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;
import lombok.*;
import com.ruoyi.common.core.page.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import cnhy.salary.domain.LeaveRecord;
//import cnhy.salary.service.LeaveRecordService;
import ling.common.*;
import ling.common.domain.*;

 /** 请假记录 控制层
 * @author : He-LiangLiang@Outlook.com
 * @date : 2025-5-26
 */
@Api(tags = "请假记录 功能接口")
@RestController
@RequestMapping("/salary/LeaveRecord")
public class LeaveRecordController extends EQueryController<LeaveRecord>{



    @ApiOperation("详情")
    @PreAuthorize("@ps.any(@pay.leaveRecord.query)")
    @GetMapping(value = "/{id}")
    public Result<LeaveRecord> getInfo(@PathVariable("id") Long id)
    {
       return super.getInfo(id);
    }

    @Resource
    EmployeeSvc employeeSvc;
    @ApiOperation("分页列表")
    @PreAuthorize("@ps.any('pay:leaveRecord:list')")
    @GetMapping("list")
    @DataScope
    public ResultRows<LeaveRecord> list(LeaveRecord dto, PageDomain pageRequest) {
        var rows=queryPage(dto,pageRequest);


        employeeSvc.employeeDtoFindSet(rows.getData(),p->p.getUserId(),(p,p1)->{
            p.ExtendMapSet("employeeDto",p1);
        });
        return rows;
    }

//     @Override
//     protected ResultRows<LeaveRecord> queryPage(Serializable whereObj, PageDomain pageRequest) {
//         gainPageDomain(pageRequest);
//         var dto = (LeaveRecord) whereObj;
//         Long[] deptIds;
//         if (Objects.equals(dto.getDeptId() , -100L)) {
//             var childList = queryHelper.entityQuery(Department.class).includes(p -> p.childList()).whereById(getDeptId()).toList();
//             deptIds = childList.stream().map(p -> p.getDeptId()).toArray(Long[]::new);
//         } else {
//             deptIds = null;
//         }
//         var pitem = queryHelper.query().queryable(tClass)
//                 .whereObject(whereObj != null, whereObj)
//                 .where(deptIds != null, p -> p.in(LeaveRecord::getDeptId, deptIds));
//
//         if (pageRequest instanceof ObjectSort)
//             pitem.orderByObject((ObjectSort) pageRequest);
//         var pData = pitem.orderByDesc(p -> p.column(LeaveRecord::getId)).toPageResult(pageRequest.getPageNum(), pageRequest.getPageSize());
//         return toResultRows(pData);
//     }

     @ApiOperation("新增")
    @PreAuthorize("@ps.any(@pay.leaveRecord.add)")
    @Log(title = "请假记录", businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated @RequestBody LeaveRecord entity) {
        if(entity.getDuration()==null)
            return  Result.bad("请假时长不能为空");
         var emplDto = queryHelper.queryable(EmployeeDto.class).where(p -> p.eq(Employee::getUserId, entity.getUserId())).firstOrNull();
         if (emplDto == null)
             return Result.bad("请检查用户是否正确！");
         var record=queryHelper.entityQuery(LeaveRecord.class)
                         .where(p->p.userId().eq(entity.getUserId()))
                                 .where(p->p.beginTime().eq(entity.getBeginTime()))
                                         .firstOrNull();
         if (record!=null){
             return Result.bad("已重复请假");
         }
         entity.setDeptId(emplDto.getDeptId());
         entity.setLv2Name(emplDto.getDeptName());
         entity.setPhone(emplDto.getPhone());
         //var m = DateUtil.between(entity.getBeginTime(), entity.getEndTime(), DateUnit.MINUTE);
         //entity.setDuration((double) m);
         if (entity.skipApprovalBy100()) {  //pc端管理员直接设置，应验证权限

         } else if (WageDictCfg.cfg().openApprovalLeaveRecord)
             entity.approval(1, null, null);
         else entity.setStatus(100);
         var re= super.add(entity);
         wageSvc.leaveToWage(entity);
         return re;
     }
     @ApiOperation("批量新增")
     @PreAuthorize("@ps.any(@pay.leaveRecord.add)")
     @Log(title = "请假记录", businessType = BusinessType.INSERT)
     @PostMapping("adds")
     public Result adds(@Validated @RequestBody LeaveRecord[] entitys) {
         if(entitys[0].getDuration()==null)
             return  Result.bad("请假时长不能为空");
         var list = new ArrayList<LeaveRecord>();
         for (var entity : entitys) {
             var emplDto = queryHelper.queryable(EmployeeDto.class).where(p -> p.eq(Employee::getUserId, entity.getUserId())).firstOrNull();
             if (emplDto == null)
                 return Result.bad("请检查用户是否正确！" + entity.getUserId());
             entity.setDeptId(emplDto.getDeptId());
             entity.setLv2Name(emplDto.getDeptName());
             entity.setPhone(emplDto.getPhone());
//             var m = DateUtil.between(entity.getBeginTime(), entity.getEndTime(), DateUnit.MINUTE);
//             entity.setDuration((double) m);
             //
             if (entity.skipApprovalBy100()) {  //pc端管理员直接设置，应验证权限

             } else if (WageDictCfg.cfg().openApprovalLeaveRecord)
                 entity.approval(1, null, null);
             else entity.setStatus(100);
             list.add(entity);
         }
         var re = super.add(list);
         for (var item : list) {
             wageSvc.leaveToWage(item);
         }
         return re;
     }
     @Resource
     WageSvc wageSvc;
     @ApiOperation(value = "审批",notes = "需要字段：id,status=100时通过-其他驳回,approvalRecord审批备注信息")
     @PreAuthorize("@ps.any(@pay.leaveRecord.edit)")
     @Log(title = "请假记录", businessType = BusinessType.UPDATE)
     @PostMapping("/approval")
    public Result approval(@RequestBody LeaveRecord entity) {
         var old = queryHelper.entityQuery(LeaveRecord.class).whereById(entity.getId()).firstOrNull();
         old.approval(entity.getStatus() == 100, entity.getApprovalRecord(), null);
         queryHelper.queryClient().updatable(old).executeRows();
         wageSvc.leaveToWage(old);
         return Result.ok();
     }

    @ApiOperation("删除")
    @PreAuthorize("@ps.any(@pay.leaveRecord.remove)")
    @Log(title = "请假记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result remove(@PathVariable("ids") Long[] ids){
        return super.remove(Arrays.stream(ids).toArray());
    }

    @ApiOperation("编辑")
    @PreAuthorize("@ps.any(@pay.leaveRecord.edit)")
    @Log(title = "请假记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public  Result edit(@Validated @RequestBody LeaveRecord entity){
        return super.edit(entity);
    }

    @ApiOperation("导出")
    @PreAuthorize("@ps.any(@pay.leaveRecord.export)")
    @Log(title = "请假记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    //@DataScope
    public void export(LeaveRecord entity, PageDomain pageRequest,HttpServletResponse response)
    {
        super.export(entity,pageRequest,null,response);
    }
}
